package github._3y.concurrency;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @Auther DRevelation
 * @Date 2020-05-27 下午 14:24
 * @Desc
 */
public class SemaphoreDemo {
    public static void main(String[] args) {
        //20个人同时来买东西
        int nums = 20;
        //店里面最多只能容纳5个人
        Semaphore semaphore = new Semaphore(5);
        ExecutorService exec = Executors.newFixedThreadPool(5);
        for (int i = 0; i < nums; i++) {
            int finalI = i;
            exec.submit(() -> {
                try {
                    semaphore.acquire();
                    System.out.println("【" + Thread.currentThread().getName() + "】 顾客" + finalI + "在挑选商品...");
                    TimeUnit.SECONDS.sleep(1);
                    System.out.println("顾客" + finalI + "购买完毕...");
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
    }
}
